package cn.yangliu.jwt.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨柳
 * @contact QQ: 574789490
 * @date 2019-04-18 10:38
 * @desp
 */
@Accessors(chain = true)
@ApiModel
@Entity
@EqualsAndHashCode(callSuper = false)
@Getter
@NoArgsConstructor
@Setter
@Table(name = "user")
@ToString
public class User implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * 用户主键
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ApiModelProperty(value = "用户主键")
    private Long id;

    /**
     * 用户名
     */
    @Column(name = "username")
    @ApiModelProperty(value = "用户名")
    private String username;

    /**
     * 用户密码
     */
    @Column(name = "password")
    @ApiModelProperty(value = "用户密码")
    private String password;

    /**
     * 版本号
     */
    @Column(name = "create_time")
    @ApiModelProperty(value = "版本号")
    private LocalDateTime createTime;

    @ManyToMany(cascade = CascadeType.ALL, targetEntity = Role.class,fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")
            , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
    private List<Role> roles = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream().map(r -> new SimpleGrantedAuthority(r.getRoleName())).collect(Collectors.toSet());
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
